package _18_剑指OfferII;

import java.util.ArrayList;
import java.util.List;

public class _084_剑指OfferII含有重复元素集合的全排列 {

    public static void main(String[] args) {

        _084_剑指OfferII含有重复元素集合的全排列 v = new _084_剑指OfferII含有重复元素集合的全排列();


        int[] ins = {1, 1, 2};
        List<List<Integer>> lists = v.permuteUnique(ins);

        for (List<Integer> list : lists) {
            System.out.println(list);
        }


    }

    private List<List<Integer>> result = new ArrayList<>();

    public List<List<Integer>> permuteUnique(int[] nums) {

        dfs(nums, 0, new ArrayList<>());

        return result;
    }

    private void dfs(int[] nums, int index, List<Integer> list) {
        int len = nums.length;
        if (index == len) {
            result.add(new ArrayList<>(list));
            return;
        }

        for (int i = index; i < len; i++) {
            if (!isRepeat(nums, i, index)) {
                list.add(nums[i]);
                swap(nums, index, i);
                dfs(nums, index + 1, list);
                swap(nums, index, i);
                list.remove(list.size() - 1);
            }
        }

    }

    private boolean isRepeat(int[] nums, int i, int index) {
        for (int j = i - 1; j >= index; j--) {
            if (nums[j] == nums[i]) return true;
        }
        return false;
    }

    private void swap(int[] nums, int index1, int index2) {
        int temp = nums[index1];
        nums[index1] = nums[index2];
        nums[index2] = temp;
    }


}
